package com.ls.utils;


import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * @ClassName AesUtil
 * @Description AES算法
 * @Author TangQuanBin
 * @Date 2019/9/17 18:52
 * @Version 1.0
 **/
public class AesUtil {

    private static int KEY_LENGTH = 16;

    /**
     * 加密
     *
     * @param word 需要加密的内容
     * @param sKey 秘钥
     * @return
     * @throws Exception
     */
    public static String encrypt(String word, String sKey) throws Exception {
        if (null == word) {
            return null;
        }
        sKey = verifyKey(sKey);
        if (StringUtils.isBlank(sKey)) {
            return null;
        }
        byte[] raw = sKey.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(word.getBytes(StandardCharsets.UTF_8));
        //此处使用BASE64做转码功能，同时能起到2次加密的作用。
        return String.valueOf(Hex.encodeHex(encrypted));
    }

    /**
     * 解密
     *
     * @param word 需要解密的内容
     * @param sKey 秘钥
     * @return
     * @throws Exception
     */
    public static String decrypt(String word, String sKey) throws Exception {
        if (null == word) {
            return null;
        }
        sKey = verifyKey(sKey);
        if (StringUtils.isBlank(sKey)) {
            return null;
        }
        byte[] raw = sKey.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        //先用base64解密
        byte[] original = cipher.doFinal(Hex.decodeHex(word.toCharArray()));
        return new String(original, StandardCharsets.UTF_8);
    }

    /**
     * 校验key是否是合法的
     * <p>
     * 此类使用AES-128-ECB加密模式，key需要为16位。
     *
     * @param sKey 16位秘钥
     * @return
     */
    private static String verifyKey(String sKey) {
        // 判断Key是否正确
        if (sKey == null) {
            System.out.print("Key为空null");
            return null;
        }
        // 判断Key是否为指定位数
        if (sKey.length() != KEY_LENGTH) {
            System.out.print("Key长度不是" + KEY_LENGTH + "位");
            return null;
        }
        return sKey;
    }


}
